package com.wswy.wzcx.ui.other

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.annotation.WorkerThread
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.RomUtils
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.UpgradeModel
import com.wswy.wzcx.module.base.onSuccess
import timber.log.Timber

object UpdateTools {

    private const val XIAOMI_MARKET = "com.xiaomi.market"
    private const val HUAWEI_MARKET = "com.huawei.appmarket"
    private const val OPPO_MARKET = "com.oppo.market"
    private const val VIVO_MARKET = "com.bbk.appstore"
    private const val LENOVO_MARKET = "com.lenovo.leos.appstore"
    private const val MEIZU_MARKET ="com.meizu.mstore"

    private const val YYB_MARKET = "com.tencent.android.qqdownloader"

    private val romHandler = hashMapOf<String,((Intent)->Boolean)>().apply {
        put("mi",::xiaomi)
        put("huawei",::huawei)
        put("oppo",::oppo)
        put("vivo",::vivo)
        put("lianxiang",::lenovo)
        put("meizu",::meizu)
    }


    @WorkerThread
    fun canShowUpgradeDialog(upgradeModel: UpgradeModel?):Boolean{
        upgradeModel?:return false
        //线上版本号大于当前版本
        if (upgradeModel.versionCode?:0 > BuildConfig.VERSION_CODE){
            val localMarketIntent = getLocalMarketIntent(AppContext.getContext(), upgradeModel.channels)
            upgradeModel.jumpMarket = localMarketIntent?.first
            return localMarketIntent != null
        }
        return false
    }

    fun hasNewVersion(upgradeModel: UpgradeModel?):Boolean{
        upgradeModel?:return false
        return upgradeModel.versionCode?:0 > BuildConfig.VERSION_CODE
    }


    private fun getLocalMarketIntent(context: Context,channels:String?):Pair<String,Intent>?{
        val intent = Intent(Intent.ACTION_VIEW)

        val uri = Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}")
        intent.setData(uri)

        var market = ""
        channels?.split(',')?.forEach {
            if (romHandler[it]?.invoke(intent) == true){
                market = it
                return@forEach
            }
        }

        Timber.e("------------ $intent")

        if (intent.getPackage().isNullOrEmpty()){

            if (!yyb(intent)){
                //如果应用宝也没有
            }
            return null
        }
        val infos= AppContext.getContext().packageManager.queryIntentActivities(intent, 0)

        infos?.forEach {
            Timber.e("$it")
        }?:kotlin.run {
            Timber.e("--------not found !")
        }

        if (infos.isNotEmpty() && infos.first() != null){
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            return Pair(market,intent)
        }
        return null
    }

    fun startMarket(context: Context,upgradeModel: UpgradeModel){
        kotlin.runCatching {
            getLocalMarketIntent(context, upgradeModel.channels)?.second?.let {
                context.startActivity(it)
            }
        }
    }


    private fun xiaomi(intent: Intent):Boolean{
        if (RomUtils.isXiaomi()){
            if (AppUtils.isAppInstalled(XIAOMI_MARKET)){
                intent.setPackage(XIAOMI_MARKET)
            }
            return true
        }
        return false
    }

    private fun huawei(intent: Intent):Boolean{
        if (RomUtils.isHuawei()){
            if (AppUtils.isAppInstalled(HUAWEI_MARKET)){
                intent.setPackage(HUAWEI_MARKET)
            }
            return true
        }
        return false
    }

    private fun oppo(intent: Intent):Boolean{
        if (RomUtils.isOppo()){
            // https://open.oppomobile.com/wiki/doc#id=10176
            if (AppUtils.isAppInstalled(OPPO_MARKET)){
                intent.setData(Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}&caller_pkg=${BuildConfig.APPLICATION_ID}"))
                intent.setPackage(OPPO_MARKET)
            }
            return true
        }
        return false
    }

    private fun vivo(intent: Intent):Boolean{

        if (RomUtils.isVivo()){

            // https://dev.vivo.com.cn/documentCenter/doc/240
            val appInfo = AppUtils.getAppInfo(VIVO_MARKET)
            if (appInfo != null && appInfo.versionCode >= 3100){
                intent.setData(Uri.parse("vivomarket://details?id=${BuildConfig.APPLICATION_ID}&th_name=self_update"))
            }else{
                intent.setData(Uri.parse("market://details?id=${BuildConfig.APPLICATION_ID}&th_name=${BuildConfig.APPLICATION_ID}"))
            }
            if (appInfo != null){
                intent.setPackage(VIVO_MARKET)
            }
            return true
        }

        return false
    }

    private fun lenovo(intent: Intent):Boolean{
        if (RomUtils.isLenovo()){
            if (AppUtils.isAppInstalled(LENOVO_MARKET)){
                intent.setPackage(LENOVO_MARKET)
            }
            return true
        }
        return false
    }

    private fun meizu(intent: Intent):Boolean{
        if (RomUtils.isMeizu()){
            if (AppUtils.isAppInstalled(MEIZU_MARKET)){
                intent.setPackage(MEIZU_MARKET)
            }
            return true
        }
        return false
    }


    private fun yyb(intent: Intent):Boolean{
        if (AppUtils.isAppInstalled(YYB_MARKET)){
            intent.setPackage(YYB_MARKET)
            return true
        }

        return false
    }


}